'use strict'


const http = require('http')
const fs = require('fs')

/** ------------------解析body数据-----------------------*/

/**
 * Content-Disposition:form-data; name="file"; filename="xxx"
 * Content-type:text/plain
 * @param {string} headerData 
 */

function parseBodyHeaders(headerData){
    let hlist = headerData.split('\r\n').filter(p => p.length > 0)

    // 解析content-disposition => hlist[0]
    // 按照；切分数组，选出从第二个元素开始的数组
    let csplit = hlist[0].split('; ').splice(1)
    console.log(csplit);
    let filename
    let name
    for(let a of csplit){
        if(a.indexOf('filename') === 0){
            filename = a.substring(a.indexOf('=')+2,a.length - 1)
        }else{
            name = a.substring(a.indexOf('=')+2,a.length - 1)

        }
    }

    let headers = {}
    let ind = 0
    let k
    for(let h of hlist){
        ind = h.indexOf(':')
        k = h.substring(0,ind).toLowerCase()
        headers[k] = h.substring(ind+1).trim()
    }

    return {
        filename,
        name,
        headers,
        contentType:headers['content-type'] || ''

    }
}


function parseBody(bodyData,headers){
    console.log(headers);
    console.log(bodyData.toString());
    let ctype = headers['content-type']

    let bdy = ctype.substring(ctype.indexOf('=')+1)

    let crlf_bdy = `\r\n--${bdy}`

    let header_end_index = bodyData.indexOf('\r\n\r\n',crlf_bdy.length);
    let headerData = bodyData.toString('utf8',crlf_bdy.length,header_end_index);

    console.log(headerData);
    // 解析文件头信息
    let hd = parseBodyHeaders(headerData)

    let file = {
        start:header_end_index+4,
        end:bodyData.indexOf(crlf_bdy,header_end_index),
        ...hd
    }

    file.length = file.end - file.start

    return file
}


/** ------------------解析body数据-END-----------------------*/

/**
 * .jpg .jpeg   ->image.jpeg
 * 
 * .png   ->image/png
 * 
 * .gif  -> image/gif
 * 
 * .ico   ->image/x-icon
 * 
 * .txt   ->text/plain
 * 
 * .json   -> text/json   或   application/json
 * 
 * .xml   ->textxml   或 aplication/xml
 */





let html = `
        <!DOCTYPE html>
        <html>
            <head>
                <title>first HTTP </title>
            </head>
            <body>
                你好.
            </body>
        </html>
    `;

let routerTable = {
    GET : {
        '/':async(req,res)=>{
            res.setHeader('content-type',
                'text/html;charset=utf-8')
            res.end(html);
        },
        '/test':async(req,res)=>{
            let status = parseInt(Math.random() * 200)+199
            res.statusCode = status
            res.end('test end')
        },

        '/upload':async(req,res) =>{
            let stm = fs.createReadStream('./upload.html')
            stm.pipe(res,{end:false})
            stm.on('end',()=>{
                res.end()
            })
        }
    },

    POST : {
        '/data':async(req,res)=>{
            let bufferList = []
            let bufferLength = 0

            
            req.on('data',chunk=>{
                bufferLength += chunk.length
                bufferList.push(chunk)
            })
            let bodyData = null;
            req.on('end',()=>{
                if(bufferList.length > 0){
                    bodyData = Buffer.concat(bufferList,bufferLength);
                    bufferList = [];
                }


                let file = parseBody(bodyData,req.headers)
                console.log(file)

                if(bodyData){
                    res.end(bodyData);
                }else{
                    res.end()
                }
            })
        }
    }
    
    
}
http.createServer((req,res)=>{


    let rm = routerTable[req.method];
    if(!rm || !rm[req.url]){
        res.statusCode = 404
        res.end('page not found')
        return
    }
    rm[req.url](req,res)
    // console.log(req);
    
    // res.setHeader('content-type',
    //     'text/plain;charset=utf-8')   //输出html文本

    
}).listen(3456)